import { app, shell, BrowserWindow, ipcMain, session } from 'electron'
import path, { join, resolve } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.ico?asset'
import Store from 'electron-store'
import log from './helper/log'
import { initMainEventsListen } from './listenEvents'

Store.initRenderer()
app.commandLine.appendSwitch('enable-features', 'SharedArrayBuffer')

const vueDevToolsPath = path.resolve('extension/vue-devtools')
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'
const openDevTools = true

function createWindow(): void {
  // Create the browser window.
  const  pid = process.pid
  console.log(`pid: ${pid}`)
  const openSessionIsolation = true
  const mainWindow = new BrowserWindow({
    width: 1024,
    height: 768,
    show: false,
    autoHideMenuBar: true,
    icon: icon,
    // titleBarStyle: "hidden",
    // backgroundColor: '#88B0F8',
    webPreferences: {
      webSecurity: false,
      allowRunningInsecureContent: true,
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      partition: openSessionIsolation ? `${pid}` : null,
    }
  } as any)

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev) {
    console.log(`load vue devtools, path: ${vueDevToolsPath}`)
    session.defaultSession.loadExtension(vueDevToolsPath)
  }
  if (openDevTools) {
    mainWindow.webContents.on('did-finish-load', () => {
      mainWindow.webContents.openDevTools()
    })
  }
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'))
  }
}


app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.electron')
  session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {

    const csp = details.requestHeaders['Content-Security-Policy']
    if (csp) {
      details.requestHeaders['Content-Security-Policy'] = csp.replace(
        'default-src \'self\'',
        'default-src \'self\'; media-src *'
      )
    }
    callback({ cancel: false, requestHeaders: details.requestHeaders })
  })
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })


  createWindow()

  app.on('activate', function() {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})


app.on('window-all-closed', () => {
  log.log('window-all-closed')
  if (process.platform !== 'darwin') {
    app.quit()
  }
})


initMainEventsListen()
